/**
 * Copyright 2015 jianglibo@gmail.com
 *
 */
package com.m3958.logcollector.passwordvalidator;

/**
 * @author jianglibo@gmail.com
 *         2015年12月25日
 *
 */
public class SequenceValidator implements PasswordValidateMethod {
    
    private final int sequence;
    
    public SequenceValidator(int sequence) {
        this.sequence = sequence;
    }

    /* (non-Javadoc)
     * @see com.m3958.logcollector.passwordvalidator.PasswordValidateMethod#validate(java.lang.String)
     */
    @Override
    public void validate(String password) throws PasswordValidatorException {
        char[] chars = password.toCharArray();
        sequenceOrdered(chars, true);
        sequenceOrdered(chars, false);
    }

    private void sequenceOrdered(char[] chars, boolean isInc) throws PasswordValidatorException {
        int maxsq = 0;
        int sq = 0;
        int inc = isInc ? 1 : -1;
        for (int i = 0; i < chars.length - 1; i++) {
            if (chars[i] + inc == chars[i + 1]) {
                sq++;
            } else {
                if (sq > maxsq) {
                    maxsq = sq;
                }
                sq = 0;
            }
        }
        
        if (sq > maxsq) {
            maxsq = sq;
        }
        
        if (maxsq >= getSequence()) {
            throw new PasswordValidatorException("MAX_SEQUENCE");
        }
    }

    public int getSequence() {
        return sequence;
    }

}
